package com.controller;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bean.Button;
import com.bean.EasyUiTreeGridBean;
import com.bean.SelectItem;
import com.common.GlobalPara;
import com.common.base.BaseController;
import com.common.exception.AppException;
import com.common.utils.IdUtil;
import com.common.utils.MD5Util;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.model.Function;
import com.model.Role;
import com.model.RoleFunction;
import com.model.User;
import com.service.UserService;
@Before(Tx.class)
public class UserController extends BaseController {
	private static final Log log = Log.getLog(UserController.class);
	public void queryUsers() {
		String login_id = getPara("login_id");
		String name = getPara("name");

		if (login_id == null) {
			login_id = "";
		}
		if (name == null) {
			name = "";
		}
		login_id = login_id + "%";
		name = name + "%";
		List<User> list = UserService.service.queryUsers(login_id, name);
		refreshDataGrid(list);
	}

	public void enterUsermanage() {
		render("userManage.jsp");
	}

	public void enterUseradd() {
		List<Role> list = Role.dao.find("SELECT roleid ,name  from role");
		List<SelectItem> dsCode = new ArrayList<SelectItem>();
		for(Role role:list){
			dsCode.add(new SelectItem(role.getRoleid(), role.getName()));
		}
		setAttr("dsRole", dsCode);
		render("userAdd.jsp");
	}

	public void userAdd() throws NoSuchAlgorithmException {
		User user = getModel(User.class, "user");
		if (user.getLoginId() == null || "".equals(user.getLoginId())) {
			throw new AppException("登录名为空");
		}
		if (user.getPassword() == null || "".equals(user.getPassword())) {
			throw new AppException("密码为空");
		}
		if (user.getName() == null || "".equals(user.getName())) {
			throw new AppException("姓名为空");
		}
		if(user.getRoleid()==null || "".equals(user.getRoleid())){
			throw new AppException("角色为空！");
		}
		if(!UserService.service.getUserByLoginId(user.getLoginId())){
			throw new AppException("已经存在登录名为" + user.getLoginId() + "的用户");
		}
		user.setUserid(IdUtil.getId());
		user.setPassword(MD5Util.toMd5Str(user.getPassword()));//md5加密
		user.save();
		renderSuccess();
	}
	public void enterUserEdit(){
		String userid = getPara("userid");
		if(userid == null){
			throw new AppException("用户id为空!");
		}
		List<Role> list = Role.dao.find("SELECT roleid ,name  from role");
		List<SelectItem> dsCode = new ArrayList<SelectItem>();
		for(Role role:list){
			dsCode.add(new SelectItem(role.getRoleid(), role.getName()));
		}
		setAttr("dsRole", dsCode);
		User user = User.dao.findById(userid);
		getRequest().setAttribute("user", user);
		render("userEdit.jsp");
	}
	
	public void enterUserView(){
		String userid = getPara("userid");
		if(userid == null){
			throw new AppException("用户id为空!");
		}
		List<Role> list = Role.dao.find("SELECT roleid ,name  from role");
		List<SelectItem> dsCode = new ArrayList<SelectItem>();
		for(Role role:list){
			dsCode.add(new SelectItem(role.getRoleid(), role.getName()));
		}
		setAttr("dsRole", dsCode);
		User user = User.dao.findById(userid);
		getRequest().setAttribute("user", user);
		render("userView.jsp");
	}
	public void userEdit() throws NoSuchAlgorithmException{
		User user = getModel(User.class,"user");
		if (user.getUserid() == null || "".equals(user.getUserid())) {
			throw new AppException("用户id为空!");
		}
		if (user.getLoginId() == null || "".equals(user.getLoginId())) {
			throw new AppException("登录名为空");
		}
		if (user.getPassword() == null || "".equals(user.getPassword())) {
			throw new AppException("密码为空");
		}
		if (user.getName() == null || "".equals(user.getName())) {
			throw new AppException("姓名为空");
		}
		if(user.getRoleid()==null || "".equals(user.getRoleid())){
			throw new AppException("角色为空！");
		}

		if(UserService.service.getUserByLoginId(user.getLoginId())){
			throw new AppException("该用户不存在！");
		}
		log.warn("id为" + user.getUserid() + "的用户被编辑了,新的密码为" + user.getPassword()+"新的名字为" +user.getName());
		user.setPassword(MD5Util.toMd5Str(user.getPassword()));//md5加密
		user.update();
		
		renderSuccess();
	}
	public void delete(){
		String userid = getPara("userid");
		User.dao.deleteById(userid);
		renderSuccess();
	}
	public void enterRoleManage(){
		render("roleManage.jsp");
	}
	public void queryRole(){
		String name = getPara("name");
		String code = getPara("code");
		if(StrKit.isBlank(name)){
			name = "%";
		}
		if(StrKit.isBlank(code)){
			code = "%";
		}
		List<Role> result = UserService.service.queryRole(name, code);
		refreshDataGrid(result);
	}
	public void enterRoleadd(){
		render("roleAdd.jsp");
	}

	public void enterRoleEdit() {
		String roleId = getPara("roleid");
		if(StrKit.isBlank(roleId)){
			throw new AppException("选中的角色不存在!");
		}
		Role role = Role.dao.findById(roleId);
		setAttr("role", role);
		render("roleEdit.jsp");
	}
	public void roleAdd(){
		Role role = getModel(Role.class, "role");
		if(StrKit.isBlank(role.getName())){
			throw new AppException("角色名称为空!");
		}
		if (StrKit.isBlank(role.getCode())) {
			throw new AppException("角色编码为空!");
		}
		if(UserService.service.checkRoleCodeExists(role.getCode())){
			throw new AppException("该角色编码已经存在了!");
		}
		role.setRoleid(IdUtil.getId());
		role.save();
		renderSuccess();
	}
	public void roleEdit(){
		Role role = getModel(Role.class, "role");
		if(StrKit.isBlank(role.getRoleid())){
			throw new AppException("选中的角色不存在!");
		}
		if(StrKit.isBlank(role.getName())){
			throw new AppException("角色名称为空!");
		}
		if (StrKit.isBlank(role.getCode())) {
			throw new AppException("角色编码为空!");
		}
		if(UserService.service.checkRoleCodeExExceptSelf(role.getCode(), role.getRoleid())){
			throw new AppException("该角色编码已经存在了!");
		}
		role.update();
		renderSuccess();
	}
	public void deletRole(){
		String roleid = getPara("roleid");
		if(StrKit.isBlank(roleid)){
			throw new AppException("选中的角色不存在!");
		}
		if(UserService.service.checkRoleHasFunc(roleid)){
			throw new AppException("该角色已经被分配了权限不能删除!");
		}
		if(UserService.service.checkRoleHasUser(roleid)){
			throw new AppException("已经有用户分配了该角色不能删除!");
		}
		Role.dao.deleteById(roleid);
		renderSuccess();
	}
	public void enterRoleRightsGrant(){
		String roleid = getPara("roleid");
		if(StrKit.isBlank(roleid)){
			throw new AppException("请选中角色后操作!");
		}
		List<RoleFunction> roleFunc =  UserService.service.getSysFuncByRoleid(roleid);
		List<Function> allFunc = Function.dao.find("SELECT * from function order by sx");
		
		Map<String,String> roleFuncMap = new HashMap<String,String>();
		for(RoleFunction rf:roleFunc){
			roleFuncMap.put(rf.getFunctionid(), "");
		}
		
		EasyUiTreeGridBean treeBean, rootTreeBean =null;
		Map<String,EasyUiTreeGridBean> TempFunMap = new HashMap<String, EasyUiTreeGridBean>();
		for (Function function : allFunc) {
			treeBean = UserService.service.convertFromFunctionToEasyUiTreeGridBean(function);
			if(roleFuncMap.containsKey(treeBean.getId())){
				treeBean.setChecked(true);
			}
			if (StrKit.isBlank(function.getParentid())) {// root node
				rootTreeBean = treeBean;
			} 
			TempFunMap.put(function.getFunctionid(), treeBean);
		}
		
		if (rootTreeBean == null) {
			throw new AppException("系统菜单配置错误！");
		}

		for (Function function : allFunc) {
			//只有一 二级菜单
			if (!function.getFunctionid().equals(rootTreeBean.getId())&& function.getGnlx().equals(GlobalPara.GNLX_TREE)){
				TempFunMap.get(function.getParentid()).getChildren().add(TempFunMap.get(function.getFunctionid()));
			}else if(function.getGnlx().equals(GlobalPara.GNLX_BUTTON)){
				EasyUiTreeGridBean temp = TempFunMap.get(function.getFunctionid());
				Button btn = new Button(temp.getId(), temp.getText(), temp.getChecked());
				TempFunMap.get(function.getParentid()).getButtons().add(btn);
			}
		}
		List<EasyUiTreeGridBean> list = new ArrayList<EasyUiTreeGridBean>();
		list.add(rootTreeBean);
		setAttr("funcdata", JsonKit.toJson(list));
		setAttr("roleid", roleid);
		render("roleRightsGrant.jsp");
	}
	public void saveRights(){
		String checkedMenuStr = getPara("checkedMenuStr");
		String checkedButtonStr = getPara("checkedButtonStr");
		String roleid = getPara("roleid");
		String[] checkedMenuArra = checkedMenuStr.split(",");
		String[] checkedButtonArra = checkedButtonStr.split(",");
 		UserService.service.deleteRoleFunc(roleid);
		List<RoleFunction> list = new ArrayList<RoleFunction>();
		RoleFunction temp;
		for(String id:checkedMenuArra){
			if(!StrKit.isBlank(id)){
				temp = new RoleFunction();
				temp.setRoleFuncid(IdUtil.getId());
				temp.setRoleid(roleid);
				temp.setFunctionid(id);
				list.add(temp);
			}
		}
		Db.batchSave(list, list.size());
		
		list.clear();
		for(String id:checkedButtonArra){
			if(!StrKit.isBlank(id)){
				temp = new RoleFunction();
				temp.setRoleFuncid(IdUtil.getId());
				temp.setRoleid(roleid);
				temp.setFunctionid(id);
				list.add(temp);
			}
		}
		Db.batchSave(list, list.size());
		renderSuccess();
	}
}
